package com.function.base.write;

import com.main.tcp.protocol.RequestFrame;
import com.response.ResponseData;

import java.util.List;

/**
 * 批量写状态地址功能基础类
 * @author zhujh
 */
public abstract class BaseWriteMultipleStatusFunctionAction extends BaseMultipleWriteFunctionAction {


    @Override
    public byte[] getReQuestByte() {
        int coilsCount = values.length;
        int length = 7 + coilsCount / 8 + 1;
        int bytesCount = coilsCount / 8 + 1;
        if (coilsCount % 8 == 0) {
            bytesCount = bytesCount - 1;
        }

        byte coilValue = (byte)0;
        // This is to always have a trailing zeroes at the end
        int coilsValuesLength = bytesCount + (coilsCount % 8 == 0 ? 1 : 0);
        byte[] coilsValues = new byte[coilsValuesLength];
        for (int i = 0; i < coilsCount; i++) {
            if ((i % 8) == 0) {
                coilValue = 0;
            }

            int tempValue = values[i] == 0xFF00 ? 1 : 0;
            coilValue = (byte)(tempValue << (i % 8) | (int)coilValue);
            coilsValues[i / 8] = coilValue;
        }

        super.setLENGTH(length);
        RequestFrame requestFrame = getRequestFrameByFunction()
                .appendData(writingAddress)
                .appendData((short)coilsCount)
                .appendData((byte)bytesCount)
                .appendData(coilsValues);

        return requestFrame.toRequest();
    }


    @Override
    public void validateSendDataParams() {
        super.validDateStartAddress(writingAddress);
        this.validDateValue(values);
    }

    public void validDateValue(int[] values) {
        for (int i = 0; i < values.length ; i++) {
            if (values[i] < 0 && values[i]  > 1) {
                throw new IllegalArgumentException("值只能是0或1");
            }
        }
    }

    @Override
    public List<ResponseData> getResPonseData(byte[] response) {
        return null;
    }

}
